package com.alex.space.commons.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author Alex
 *         Created by Alex on 2017/12/27.
 */
public class ReflectTest {

    public static void main(String[] args) throws Throwable {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Class clazz = loader.loadClass("com.alex.space.commons.reflect.Car");

        //获取默认构造函数
        Constructor cons = clazz.getDeclaredConstructor((Class[]) null);
        Car car = (Car) cons.newInstance();

        Method setBrand = clazz.getMethod("setBrand", String.class);
        setBrand.invoke(car, "BMW");
        Method setColor = clazz.getMethod("setColor", String.class);
        setColor.invoke(car, "Black");
        Method setMaxSpeed = clazz.getMethod("setMaxSpeed", int.class);
        setMaxSpeed.invoke(car, 240);

        Field field = clazz.getDeclaredField("brand");
        field.setAccessible(true);
        field.set(car, "BENZ");

        Method drive = clazz.getDeclaredMethod("drive", (Class[]) null);
        drive.setAccessible(true);
        drive.invoke(car);
        
        car.introduce();

        System.out.println("current loader: " + loader);
        System.out.println("parent loader: " + loader.getParent());
        System.out.println("grandparent loader: " + loader.getParent().getParent());
    }
}
